<template>
  <el-row class="point-type-info-form" type="flex" justify="center">
    <el-col>
      <el-form label-width="125px" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
        <input type="hidden" v-model="editForm.id" />
        <el-form-item label="点位类别名称：" prop="pointTypeName">
          <el-input v-model="editForm.pointTypeName" auto-complete="off" placeholder="不能重复"></el-input>
        </el-form-item>  
        <el-form-item label-width="0" style="padding: 0 0 20px;">
          <el-tabs v-model="activeTabsValue" type="card" closable @tab-remove="removeTab">
            <el-tab-pane v-for="item in editableTabs2" :key="item.name" :label="item.title" :name="item.name">
              <el-form-item label="内容名称：" :prop="'content_' + item.name">
                <el-input v-model="item.content"></el-input>
              </el-form-item>
              <el-form-item class="check-type" label="检查项类型：">
                <el-radio-group v-model="item.optionType" size="medium">
                  <!-- <el-radio :label="0">默认配置</el-radio>
                  <el-radio :label="1">单选项</el-radio> -->
                  <el-radio :label="1">合格/不合格类</el-radio>
                  <el-radio :label="2">单选类</el-radio>
                  <el-radio :label="3">填值类</el-radio>
                  <el-radio :label="4">拍照类</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-card v-if="item.optionType">
                <template v-if="item.optionType === 1">
                  <!-- 合格/不合格类 -->
                  <el-form-item v-for="(attrObj,attrIndex) in item.attr.length > 0 ? item.attr : item.attr.push({option: '',isOK: true}, {option: '',isOK: false})" :key="attrObj.id" >
                    <el-row :gutter="12">
                      <el-col :span="14">
                        <el-input v-if="attrIndex == 0" v-model="attrObj.option" placeholder="请输入选项A" disabled></el-input>
                        <el-input v-else v-model="attrObj.option" placeholder="请输入选项B" disabled></el-input>
                      </el-col>
                      <el-col :span="7">
                        <el-checkbox  v-if="attrIndex != 0" disabled checked>
                          设为不合格
                        </el-checkbox>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </template>
                <template v-if="item.optionType === 2">
                <!-- 单选类 -->
                  <el-form-item
                    v-for="(attrObj, attrindex) in item.attr.length>0?item.attr:item.attr.push({option:'',isOk:false}, {option:'',isOk:true})"
                    :key="attrObj.id">
                    <el-row :gutter="12">
                      <el-col :span="14">
                        <el-input v-model="attrObj.option" placeholder="请输入检查项"></el-input>
                      </el-col>
                      <el-col :span="7">
                        <el-checkbox @change="attrObj.isOk=!attrObj.isOk" :checked="attrObj.isOk?false:true">设置为不合格</el-checkbox>
                      </el-col>
                      <el-col :span="3">
                        <el-button
                          v-if="attrindex===0"
                          type="primary"
                          icon="el-icon-plus"
                          @click.prevent="addDomain(item.attr)">
                          <!--新增-->
                        </el-button>
                      </el-col>
                      <el-col :span="3">
                        <el-button
                          v-if="attrindex > 1"
                          type="danger"
                          icon="el-icon-delete"
                          @click.prevent="removeDomain(item.attr,attrindex)">
                          <!--删除-->
                        </el-button> 
                      </el-col>
                    </el-row>
                  </el-form-item>
                </template>
                <template v-if="item.optionType === 3">
                  <!-- 填值类 -->
                  <el-row>
                    <el-col :span="14">
                      <el-form-item label="上限">
                        <el-input v-model="upperLimit" type="number" placeholder="请输入数字"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="14">
                      <el-form-item label="下限">
                        <el-input v-model="lowerLimit" type="number" placeholder="请输入数字"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="14">
                      <el-form-item label="单位">
                        <el-input v-model="unit" type="text" placeholder="请输入单位，比如米"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>       
                </template>
                <template v-if="item.optionType === 4">
                  <el-row>
                    <el-col :span="14">
                      <el-form-item label="最少拍照数量：">
                        <el-input v-model="photographNumber" type="number" max="9" placeholder="输入数字，不超过9"></el-input>
                      </el-form-item>
                    </el-col>
                    <span style="margin-left: 8px;">张</span>
                  </el-row>
                </template>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>

        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeDialog()">取消</el-button>
          <el-button type="primary" round @click="addTab()">添加检查内容</el-button>
          <el-button type="primary" round @click="savePointType('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import { addInspectPointType } from '@/api/inspect'

export default {
  name: 'PointTypeMaintain',
  props: {
    editInfo: {         // 行信息
      type: Object,       
      required: false,  
    },
    closeDialog: {     // 关闭对话框
      type: Function,
      required: true,
    },
  },
  data() {
    return {
      qiniuData: {      //上传图片携带的参数       
        token: '',
        key: '',
        fileList: [],
      },

      defaultImg: this.GLOBAL.defaultImg,
      
      util: util,             // 工具方法
      
      activeTabsValue: '1',   // 当前活跃标签
      
      editableTabs2: [],      // 自定义标签

      editForm: {             // 编辑表单
        id: '',               // 不知道什么id
        orgId: this.$store.state.userinfo.org.id,   // 单位id ???
        pointTypeName: '',                          // 点位名称 
        picUrl: '',
        createAccount: this.$store.state.userinfo.accountName, // 创建的账户
        updateAccount: this.$store.state.userinfo.accountName, // 更新的账户
        contents: '',                                          // 不知道什么内容
      },

      upperLimit: '',                                          // 上限
      lowerLimit: '',                                          // 下限
      unit: '',                                                // 单位
      photographNumber: '',                                    // 照片数量 

      editFormRules: {                                         // 表单约束规则
        pointTypeName: [
          { required: true, message: '请输入点位类别名称', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    let infoObj = this.editInfo
    if (infoObj.id) {
      //编辑
      this.editForm.id = infoObj.id
      this.editForm.orgId = infoObj.orgId
      this.editForm.pointTypeName = infoObj.pointTypeName
      this.editForm.picUrl = infoObj.picUrl
      infoObj.picUrl
        ? $.each(infoObj.picUrl.split(','), (index, url) => {
            this.qiniuData.fileList.push({
              name: '现场图片' + index,
              url: url,
            })
          })
        : ''
      this.editForm.createAccount = infoObj.createAccount
      if (infoObj.contentList.length > 0) {
        $.each(infoObj.contentList, (index, obj) => {
          this.editableTabs2.push({
            title: '检查内容' + (index + 1),
            name: index + 1 + '',
            content: obj.content,               // 内容名称
            attr: obj.attr,                     // 合格 / 不合格
            optionType: obj.optionType,         // 0默认 1单选
            sort: obj.sort,
          })
        })
      } else {
        // 默认添加一个检查项
        this.addTab()
      }                                                                                   
    } else {
      // 默认添加一个检查项
      this.addTab()
    }
    this.getToken() //获取token
  },
  methods: {
    validateContent(rule, value, callback) {
      let that = this
      let index = Number(rule.field.split('_')[1]) - 1
      if (!that.editableTabs2[index].content) {
        callback(new Error('请输入内容名称'))
        that.activeTabsValue = String(rule.field.split('_')[1])
      } else {
        callback()
      }
    },
    addDomain(attrArr) {
      return attrArr.push({
        option: '',
        isOk: true,
      })
    },
    removeDomain(attrArr, attrindex) {
      return attrArr.splice(attrindex, 1)
    },
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.qiniuData.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    addTab() {
      let newTabName =
        this.editableTabs2.length > 0
          ? this.editableTabs2[this.editableTabs2.length - 1]['sort'] + 1 + ''
          : '1'
      this.editableTabs2.push({
        title: '检查内容' + newTabName,
        name: newTabName,
        content: '',
        attr: [],
        optionType: 0, //0默认 1单选
        sort: parseInt(newTabName),
      })
      // 添加校验规则
      this.editFormRules['content_' + newTabName] = [
        { required: true, validator: this.validateContent, trigger: 'change' },
      ]
      this.activeTabsValue = newTabName
    },
    removeTab(targetName) {
      let tabs = this.editableTabs2
      let activeName = this.activeTabsValue
      if (tabs.length > 1) {
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        this.activeTabsValue = activeName
        this.editableTabs2 = tabs.filter((tab) => tab.name !== targetName)
      } else {
        this.$message({
          message: '检查内容至少存在一条',
          type: 'warning',
        })
      }
    },
    checkTypeValidate() {
      let that = this
      let flag = true
      let data = that.editableTabs2

      for (let i = 0, len = data.length; i < len; i++) {
        if (data[i].optionType == 1 && flag) {
          // 是否存在两种不同结果（合格、不合格）
          let hasDiffResult = false
          for (let j = 0, num = data[i].attr.length; j < num; j++) {
            // 检查项为空
            if (data[i].attr[j].option == '') {
              that.activeTabsValue = String(i + 1)
              that.$message({
                type: 'warning',
                message: `请输入“${data[i].title}”中的检查项`,
              })
              flag = false
              return false
            } else if (data[i].attr[j].isOk != data[i].attr[0].isOk) {
              hasDiffResult = true
            }
          }
          if (!hasDiffResult) {
            that.activeTabsValue = String(i + 1)
            that.$message({
              type: 'warning',
              message: `请正确设置“${data[i].title}”中的状态，需同时存在合格、不合格两种不同状态`,
            })
            flag = false
            return false
          }
        }
      }
      return flag
    },
    savePointType(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          // 检测是否有合格和不合格两种情况
          if (that.checkTypeValidate()) {
            let parames = that.editForm
            parames.picUrl = util.ilinkArrHandle
              .getqiniuPicUrlArr(this.qiniuData.fileList)
              .toString()
            parames.contents = JSON.stringify(that.editableTabs2)
            addInspectPointType(parames).then((res) => {
              that.$message({
                message: '保存成功！',
                type: 'success',
              })
              that.closeDialog(true)
            })
          }
        } else {
          return false
        }
      })
    },
  },
}
</script>
<style lang="scss">
.point-type-info-form {
  .add-tab-btn {
    position: absolute;
    top: -45px;
    right: 0;
  }
  .check-type {
    margin-top: 10px;
    .el-form-item__label {
      float: left;
    }
  }
  .el-row {
    margin-bottom: 10px;
  }
  .el-card {
    margin-top: 20px;
  }
}
</style>
